#include <stdio.h>
#include <sys/time.h>
#include <sys/times.h>
#include <atmi.h>
#include <fml32.h>
#include <Usysfl32.h>
#include <tpadm.h>

#include <errno.h>
#include <fcntl.h>

#define	MAXSRV	600

struct usrvinfo {
	char	name[32]	[MAXSRV];
	long	srvid		[MAXSRV];
	long	pid		[MAXSRV];
	char	svcrname[32]	[MAXSRV];
};
typedef struct usrvinfo USRVINFO;

FBFR32 	*sendbuf, *rcvbuf;

int ux_svcactv( char *svc_name )
{
	USRVINFO	srv, *psrv;
	long		occurs;
	int		svc_cnt;
	int		i;
	char		exec_file_name	[1024];

	if((sendbuf = (FBFR32 *)tpalloc("FML32", NULL, 1024)) == NULL) {
		printf("tpalloc error : %s\n", tpstrerror(tperrno));
		exit(1);
	}
	if((rcvbuf = (FBFR32 *)tpalloc("FML32", NULL, sizeof(USRVINFO))) == NULL) {
		printf("tpalloc error : %s\n", tpstrerror(tperrno));
		tpfree((char *)sendbuf);
		exit(1);
	}

	psrv = &srv;
	memset(psrv->name, 0x00, sizeof(psrv->name[0]));
	strcpy(psrv->name, svc_name);
	if(get_svcinfo(&occurs, psrv) != 0) {
		printf("get_svcinfo error\n");
		tpfree((char *)sendbuf);
		tpfree((char *)rcvbuf);
		exit(1);
	}

	svc_cnt = 0;
	for(i=0; i<(int)occurs; i++) {

		if( !strcmp(svc_name, psrv->svcrname[i]) )
			svc_cnt += 1;
	}

	tpfree((char *)sendbuf);
	tpfree((char *)rcvbuf);

	return(svc_cnt);
}

int get_svcinfo(long *occurs, USRVINFO *pusrv)
{
	long    i, len;
	long	ta_error;

	Finit32(sendbuf, Fsizeof32(sendbuf));
   	Finit32(rcvbuf, Fsizeof32(rcvbuf));
	Fchg32(sendbuf, TA_CLASS, 	0, "T_SVCGRP", 0);
 	Fchg32(sendbuf, TA_OPERATION, 	0, "GET", 0);
 	Fchg32(sendbuf, TA_SERVICENAME,	0, pusrv->name[0], 0);

	if(tpcall(".TMIB", (char *)sendbuf, 0, (char **)&rcvbuf, &len, TPNOTRAN|TPNOCHANGE|TPSIGRSTRT|TPNOTIME) == -1) {
		printf("tpcall failed: %s\n", tpstrerror(tperrno));
		if( tperrno == TPESVCFAIL ) {
			Fget32(rcvbuf, TA_ERROR, 0, (char *)&ta_error, 0);
			printf("get_srvinfo failure: %ld\n", ta_error);
		}
		return(-1);
	}

	Fget32(rcvbuf, TA_OCCURS, 0, (char *)occurs, 0);

	for(i=0; i<(int)*occurs; i++) {
		Fget32(rcvbuf, TA_SVCRNAM, i, (char *)pusrv->svcrname[i], 0);
	}

	return(0);
}

